package com.caigou.modules.home.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.PrizeBallItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.Banner
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.Logger
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.base.widget.VipDialog
import com.caigou.modules.home.R
import com.caigou.modules.home.bean.PrizeBean
import com.caigou.modules.home.bean.PrizeTimeBean
import com.caigou.modules.home.databinding.FragmentHomeBinding
import com.caigou.modules.home.viewmodel.HomeViewModel
import com.caigou.modules.home.widget.ScratchCardDialog
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2021/09/13
 */
@AndroidEntryPoint
class HomeFragment : BaseFragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private val homeViewModel: HomeViewModel by viewModels()

    private val banners: MutableList<String> by lazy {
        mutableListOf()
    }

    private val forwards: MutableList<String> by lazy {
        mutableListOf()
    }

    private var vipDialog: VipDialog? = null

    private var prizeType = 1

    private val nd = 24 * 60 * 60 * 1000L
    private val nh = 60 * 60 * 1000L
    private val nm = 60 * 1000L
    private val ns = 1000L
    private var countDownJob: Job? = null

    private var hkMiStatus = 0
    private var macaoMiStatus = 0
    private var twMiStatus = 0
    private var singaporeMiStatus = 0

    private val mAdapter: PrizeBallItemAdapter by lazy {
        PrizeBallItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.homeSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchBanner()
                fetchOpenPrizeTime()
                fetchPrizeResult()
            }
        }

        binding.banner.setDelegate { banner, itemView, feedImageUrl, position ->
            openBrowser(forwards[position])
        }
        binding.banner.setAdapter { _, itemView, model, position ->
            ImageLoader.load(requireActivity(), model as String?, itemView as ImageView)
        }

        binding.homeTvChatRoom.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Hybrid.PAGE_CHAT).navigation()
        }

        binding.homeIvRedpack.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Tools.PAGE_TOOLS)
                    .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Tools.TAG_ACTIVE)
                    .navigation()
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.homeIvHelp.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Service.PAGE_SERVICE)
                .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Service.TAG_HELP)
                .navigation()
        }

        binding.homeLayoutFeature.homeFeatureLlInvite.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Tools.PAGE_TOOLS)
                    .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Tools.TAG_INVITE)
                    .navigation()
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.homeLayoutFeature.homeFeatureLlVip.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (AppBackgroundInfo.instance.userBean!!.vip == 1) {
                    showToast("您已是VIP")
                } else {
                    vipDialog?.apply {
                        if (isShowing) {
                            dismiss()
                        }
                        vipDialog = null
                    }
                    vipDialog = VipDialog(requireActivity())
                    vipDialog?.apply {
                        btnMonth.setOnClickListener {
                            dismiss()
                        }
                        btnYear.setOnClickListener {
                            dismiss()
                        }
                        show()
                    }
                }
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.homeLayoutFeature.homeFeatureLlTurntable.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Tools.PAGE_TOOLS)
                    .withString(AppConstants.TARGET_FRAGMENT_TAG, RouterPath.Tools.TAG_ACTIVE)
                    .navigation()
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.homeTvPrizeDownload.setOnClickListener {
            openBrowser("https://8888188.com")
        }

        initHomePrize()
        initHomeItem()
    }

    override fun lazyLoad() {
        fetchBanner()
        fetchOpenPrizeTime()
        fetchPrizeResult()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(homeViewModel.bannerLiveData, ::handleBanners)
        observe(homeViewModel.openPrizeTimeLiveData, ::handleGetOpenPrizeTime)
        observe(homeViewModel.prizeResultLiveData, ::handleGetPrizeResult)
        observe(homeViewModel.miStatusLiveData, ::handleSetMiStatus)
    }

    override fun onBack() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun initHomePrize() {
        binding.homeTicketRgSelector.setOnCheckedChangeListener { group, checkedId ->
            prizeType = when (group.checkedRadioButtonId) {
                R.id.home_btn_hk_ticket -> 1
                R.id.home_btn_macao_ticket -> 2
                R.id.home_btn_tw_ticket -> 3
                R.id.home_btn_singapore_ticket -> 4
                else -> 1
            }
            fetchPrizeResult()
        }

        binding.homeRecyclerViewPrize.run {
            layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        binding.homeTvPrizeHistory.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Home.PAGE_HISTORY_PRIZE)
                .withInt(AppConstants.PRIZE_TYPE, prizeType)
                .navigation()
        }

        binding.homeLlPrizeShare.setOnClickListener {
            val bitmap = binding.homeLlContainer.screenCapture()
            MediaUtils.saveBitmap(requireActivity(), bitmap)
            showToast("截图已保存到系统相册")
        }

        if (binding.homeScMi.isChecked) {
            binding.homeTvPrizeNum.visibility = View.GONE
            binding.homeTvPrizeDesc.visibility = View.GONE
            binding.homeIvGuayigua.visibility = View.VISIBLE
        } else {
            binding.homeTvPrizeNum.visibility = View.VISIBLE
            binding.homeTvPrizeDesc.visibility = View.VISIBLE
            binding.homeIvGuayigua.visibility = View.GONE
        }

        binding.homeScMi.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                binding.homeTvPrizeNum.visibility = View.GONE
                binding.homeTvPrizeDesc.visibility = View.GONE
                binding.homeIvGuayigua.visibility = View.VISIBLE
            } else {
                binding.homeTvPrizeNum.visibility = View.VISIBLE
                binding.homeTvPrizeDesc.visibility = View.VISIBLE
                binding.homeIvGuayigua.visibility = View.GONE
            }
        }
    }

    private fun initHomeItem() {
        binding.homeLayoutItem.apply {
            homeItemForum.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_forum)
                itemIvHot.visibility = View.VISIBLE
                itemTvTitle.text = "高手论坛"
                itemTvContent.text = "高手心水汇总"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM).navigation()
                }
            }
            homeItemJingpin.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_jingpin)
                itemIvHot.visibility = View.VISIBLE
                itemTvTitle.text = "精品帖子"
                itemTvContent.text = "精品帖子"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Jingpin.PAGE_JING_PIN).navigation()
                }
            }
            homeItemMarket.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_market)
                itemIvHot.visibility = View.VISIBLE
                itemTvTitle.text = "猛料市场"
                itemTvContent.text = "超准资料免费转"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Forum.PAGE_MARKET).navigation()
                }
            }
            homeItemData.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_data)
                itemTvTitle.text = "每期资料"
                itemTvContent.text = "六合玄机破解"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Data.PAGE_DATA).navigation()
                }
            }
            homeItemGallery.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_gallery)
                itemTvTitle.text = "六合图库"
                itemTvContent.text = "六合图库免费看"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Gallery.PAGE_GALLERY).navigation()
                }
            }
            homeItemMystery.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_run_dog)
                itemTvTitle.text = "跑狗玄机"
                itemTvContent.text = "新老跑狗交流分享"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Vote.PAGE_RUN_DOG).navigation()
                }
            }
            homeItemGuess.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_guess)
                itemTvTitle.text = "幽默猜测"
                itemTvContent.text = "猜一猜找特码"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Vote.PAGE_GUESS).navigation()
                }
            }
            homeItemNondescript.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_unlike)
                itemTvTitle.text = "四不像"
                itemTvContent.text = "香港挂牌竞猜"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Vote.PAGE_UNLIKE).navigation()
                }
            }
            homeItemQuery.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_query)
                itemTvTitle.text = "挑码助手"
                itemTvContent.text = "六合资讯大全集合"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Query.PAGE_WELCOME).navigation()
                }
            }
            homeItemCalendar.apply {
                itemIvIcon.setImageResource(R.drawable.img_comm_calendar)
                itemTvTitle.text = "老黄历"
                itemTvContent.text = "六合每期吉数黄历"
                root.setOnClickListener {
                    ARouter.getInstance().build(RouterPath.Hybrid.PAGE_CALENDAR).navigation()
                }
            }
        }
    }

    private fun handleBanners(result: Resource<MutableList<Banner>>) {
        when (result) {
            is Resource.Loading -> {
            }
            is Resource.DataError -> {
                binding.homeSwipeRefreshLayout.isRefreshing = false
            }
            else -> {
                binding.homeSwipeRefreshLayout.isRefreshing = false
                banners.clear()
                forwards.clear()
                result.data?.onEach {
                    banners.add(it.bannerImg)
                    forwards.add(it.forward)
                }
                binding.banner.run {
                    setAutoPlayAble(banners.size > 1)
                    setData(banners, null)
                }
            }
        }
    }

    private fun handleGetOpenPrizeTime(result: Resource<MutableList<PrizeTimeBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.homeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取开奖时间异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.homeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null || result.data!!.isEmpty()) {
                    return
                }
                result.data?.forEach { bean ->
                    if (!TextUtils.isEmpty(bean.nextOpenTime)) {
                        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                        val date = simpleDateFormat.parse(bean.nextOpenTime)
                        val calendar = Calendar.getInstance()
                        calendar.time = date
                        val month = calendar.get(Calendar.MONTH) + 1
                        val day = calendar.get(Calendar.DAY_OF_MONTH)
                        when (bean.lotteryType) {
                            1 -> binding.homeBtnHkTicket.text = "港彩\n${month}月${day}日开奖"
                            2 -> binding.homeBtnMacaoTicket.text = "澳彩\n${month}月${day}日开奖"
                            3 -> binding.homeBtnTwTicket.text = "台彩\n${month}月${day}日开奖"
                            4 -> binding.homeBtnSingaporeTicket.text = "新彩\n${month}月${day}日开奖"
                        }
                    }
                }
            }
        }
    }

    private fun handleGetPrizeResult(result: Resource<PrizeBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.homeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取开奖结果异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.homeSwipeRefreshLayout.isRefreshing = false
                if (result.data != null) {
                    handlePrizeResult(result.data!!)
                }
            }
        }
    }

    private fun handleSetMiStatus(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
            }
            is Resource.DataError -> {
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取开奖结果异常")
                }
            }
            is Resource.Success -> {
            }
        }
    }

    private fun fetchBanner() {
        homeViewModel.getBanners()
    }

    private fun fetchOpenPrizeTime() {
        homeViewModel.getOpenPrizeTime()
    }

    private fun fetchPrizeResult() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        homeViewModel.getPrizeResult(prizeType, userId)
    }


    private fun handlePrizeResult(bean: PrizeBean) {
        bean.apply {
            if (AppBackgroundInfo.instance.hasLogin) {
                binding.homeScMi.isChecked = miJiangStatus == 0
            } else {
                binding.homeScMi.isChecked = when (prizeType) {
                    1 -> hkMiStatus == 0
                    2 -> macaoMiStatus == 0
                    3 -> twMiStatus == 0
                    4 -> singaporeMiStatus == 0
                    else -> true
                }
            }
            if (prizeList.isNotEmpty()) {
                binding.homeTvPrizeTitle.text = "第${period}期开奖结果"
                val balls = prizeList.slice(0..prizeList.size - 2)
                mAdapter.setList(balls)
                val lastBall = prizeList[prizeList.size - 1]
                binding.homeTvPrizeNum.text = lastBall.number
                binding.homeTvPrizeNum.setBackgroundResource(prizeBallColor(lastBall.numberColor))
                binding.homeTvPrizeDesc.text = lastBall.animalName
                binding.homeIvGuayigua.setOnClickListener {
                    with(ScratchCardDialog(requireActivity(), lastBall) {
                        if (AppBackgroundInfo.instance.hasLogin) {
                            homeViewModel.setMiStatus(period, AppBackgroundInfo.instance.userBean!!.userId, prizeType, 1)
                        }
                        when (prizeType) {
                            1 -> hkMiStatus = 1
                            2 -> macaoMiStatus = 1
                            3 -> twMiStatus = 1
                            4 -> singaporeMiStatus = 1
                        }
                        binding.homeScMi.isChecked = false
                    }) {
                        show()
                    }
                }

                if (!TextUtils.isEmpty(nextOpenTime)) {
                    binding.homeTvPrizeNextTime.text = "下期开奖日期：${nextOpenTime}"
                    countDownJob?.apply {
                        cancel()
                        countDownJob = null
                    }
                    val startDate = date2ts(nextOpenTime)
                    countDownJob = countDownCoroutines(startDate, lifecycleScope, onTick = { time ->
                        binding.homeTvPrizeCountDown.text = "直播倒计时：$time"
                    }, null, null)
                }
            }
        }
    }

    private fun countDownCoroutines(
        startDate: Long,
        scope: CoroutineScope,
        onTick: (String) -> Unit,
        onStart: (() -> Unit)? = null,
        onFinish: (() -> Unit)? = null
    ): Job {
        return flow {
            while (true) {
                val diff = startDate - System.currentTimeMillis()
                val day = diff / nd
                val hour = diff % nd / nh
                val min = diff % nd % nh / nm
                val sec = diff % nd % nh % nm / ns
                emit("${day * 24 + hour}:$min:$sec")
                delay(1000L)
            }
        }.flowOn(Dispatchers.Main)
            .onStart { onStart?.invoke() }
            .onCompletion { onFinish?.invoke() }
            .onEach { onTick.invoke(it) }
            .launchIn(scope)
    }
}